<template>
	<custom-navigation-bar background='linear-gradient(135deg, #faed00 0%, #fdb218 25%, #d63d2d 60%, #64024d 100%);'
		class="nav-bar" title="日历" color='#FFF' :back="false"></custom-navigation-bar>
	<view class="calendar">
		<swiper style="flex: 1;" :current='current' circular @change='change'>

			<swiper-item v-for="(item,index) in 3">
				<view class="">
					<!-- 显示年份 -->
					<!-- <view class="year"></view> -->
					<!-- 显示月份 -->
					<view class="month flex-row align-end">{{ getDisplayYear(index) }} / {{ getDisplayMonth(index) }}月
						<text v-if="hasDay" class="has-day"
							style="">{{hasDay<0?`${Math.abs(hasDay)}天后`:`${hasDay}天前`}}</text>
					</view>

					<view class=" flex-row justify-between">
						<view class="day-item " v-for="(v,k) in weekList">
							{{v}}
						</view>
					</view>
					<!-- 日期网格 -->
					<view class="days-grid flex-row justify-between flex-wrap">
						<!-- 空白填充 -->
						<view class="day-item empty" v-for="(empty, eIdx) in getEmptyDaysBefore(index)"
							:key="'empty-' + eIdx"></view>

						<!-- 日期显示 -->
						<view class="" @tap="onTap(day.day,index)" :class="[day.day==nowday&&nowmonth==getDisplayMonth(index)?'now-day':'',
						 selectDay == day.day?'select-day':'day-item',
						 (day.weekday==6 || day.weekday==7) ?'week-day':''
						 ]" v-for="(day, dIdx) in getDaysData(index)" :key="dIdx">
							{{ day.day }}
						</view>

						<!-- 空白填充 -->
						<view class="day-item empty" v-for="(empty, eIdx) in getEmptyDaysAfter(index)"
							:key="'empty-after-' + eIdx"></view>
					</view>
				</view>
			</swiper-item>

		</swiper>
	</view>
</template>

<script>
	const now = new Date();
	const year = now.getFullYear();
	const currentMonth = now.getMonth() + 1; // 加 1 是因为月份从 0 开始
	// 获取今天是当月的第几天（1-31）
	const dayOfMonth = now.getDate();
	export default {
		data() {
			return {
				hasDay: null,
				nowday: dayOfMonth,
				nowmonth: currentMonth,
				selectDay: dayOfMonth,
				current: 1, // 当前显示的swiper索引（中间为当前月）
				currentYear: now.getFullYear(),
				currentMonth: now.getMonth() + 1, // 1-12
				weekList: ['一', '二', '三', '四', '五', '六', '日'],
				// 存储三个月份的数据：[上月, 本月, 下月]
				monthsData: []
			}
		},
		created() {
			this.updateMonthsData();

		},
		methods: {
			getDaysFromDate(year, month, day) {
				// 创建目标日期对象并重置时间为0点
				const targetDate = new Date(year, month - 1, day);
				targetDate.setHours(0, 0, 0, 0);

				// 创建当前日期对象并重置时间为0点
				const currentDate = new Date();
				currentDate.setHours(0, 0, 0, 0);

				// 计算毫秒差并转换为天数
				const msPerDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
				const timeDiff = currentDate - targetDate;
				const dayDiff = Math.floor(timeDiff / msPerDay);

				return dayDiff;
			},
			onTap(day, i) {
				this.selectDay = day
				this.hasDay = this.getDaysFromDate(this.getDisplayYear(i), this.getDisplayMonth(i), day)
				console.log('hasDay', this.hasDay);
			},
			/**
			 * 更新三个月的数据
			 */
			updateMonthsData() {
				// 明确计算出三个月份：上月、本月、下月
				const prevMonth = this.currentMonth - 1;
				const nextMonth = this.currentMonth + 1;
				let preMonth = this.getMonthData(prevMonth)
				let nexMonth = this.getMonthData(nextMonth)
				if (this.current == 2) {
					preMonth = this.getMonthData(nextMonth + 1)
				}
				if (this.current == 0) {
					nexMonth = this.getMonthData(prevMonth - 1)
				}
				this.monthsData = [
					preMonth,
					this.getMonthData(this.currentMonth),
					nexMonth
				];
				console.log('monthsData',this.monthsData);
			},
			/**
			 * 获取指定月份的数据（支持跨年度）
			 * @param {number} month 月份（可以是0-13，自动处理跨年）
			 * @returns {object} 月份数据
			 */
			getMonthData(month) {
				let year = this.currentYear;

				// 处理月份跨年度
				if (month < 1) {
					month = 12;
					year = this.currentYear - 1;
				} else if (month > 12) {
					month = 1;
					year = this.currentYear + 1;
				}

				// 获取当月天数
				const daysInMonth = new Date(year, month, 0).getDate();
				// 星期映射（1-7对应周一到周日）
				const weekdays = [7, 1, 2, 3, 4, 5, 6];

				// 生成每天数据
				const daysInfo = Array.from({
					length: daysInMonth
				}, (_, i) => {
					const day = i + 1;
					const date = new Date(year, month - 1, day);
					const dayOfWeek = date.getDay();

					return {
						day,
						weekday: weekdays[dayOfWeek],
						weekdayNumber: dayOfWeek
					};
				});

				return {
					year,
					month,
					daysCount: daysInMonth,
					days: daysInfo
				};
			},
			change(e) {
				const newCurrent = e.detail.current;
				// 向左滑动（下一个月）
				if (newCurrent === 0 && this.current === 2) {
					this.currentMonth += 3;
					if (this.currentMonth > 12) {
						this.currentMonth = this.currentMonth - 12;
						this.currentYear += 1;
					}
				} else if (newCurrent === 2 && this.current === 0) {
					// 向右滑动 - 上个月
					this.currentMonth -= 3;
					if (this.currentMonth < 1) {
						this.currentMonth = 12 - this.currentMonth;
						this.currentYear -= 1;
					}
				}
				// 向右滑动（上一个月）
				console.log('currentMonth', this.currentMonth);
				this.current = newCurrent;
				this.hasDay = this.getDaysFromDate(this.getDisplayYear(newCurrent), this.getDisplayMonth(newCurrent), this.selectDay)
				this.updateMonthsData();
			},
			// 以下为模板辅助方法
			getDaysData(index) {
				return this.monthsData[index].days || [];
			},

			getDisplayYear(index) {
				return this.monthsData[index].year || this.currentYear;
			},

			getDisplayMonth(index) {
				return this.monthsData[index].month || this.currentMonth;
			},

			getEmptyDaysBefore(index) {
				const firstDay = this.monthsData[index]?.days[0];
				return firstDay ? firstDay.weekday - 1 : 0;
			},

			getEmptyDaysAfter(index) {
				const lastDay = this.monthsData[index]?.days.slice(-1)[0];
				return lastDay ? 7 - lastDay.weekday : 0;
			}


		}
	}
</script>

<style lang="scss" scoped>
	.calendar {
		height: 50vh;
	}

	.month-container {
		padding: 10px;
	}

	.has-day {
		font-size: 12px;
		font-weight: 400;
		color: #444444;
	}

	.now-day {
		background: #0055ff;
		color: #FFF;
		border-radius: 10px;
	}

	.select-day {
		border: 1rpx solid #0055ff;
		border-radius: 10px;
		width: calc((100vw - 30px) / 7);
		text-align: center;
		padding: 10px 0;
		margin-bottom: 5px;
	}

	.year {
		text-align: center;
		font-size: 16px;
		margin-bottom: 5px;
		color: #666;
	}

	.month {
		// text-align: center;
		padding: 10px 0;
		font-size: 20px;
		font-weight: bold;
	}

	.week-header {
		margin-bottom: 10px;
	}

	.days-grid {
		row-gap: 10px;
	}

	.day-item {
		width: calc((100vw - 30px) / 7);
		text-align: center;
		padding: 10px 0;
		border: 1rpx solid #0055ff00;
		margin-bottom: 5px;

		&.empty {
			visibility: hidden; // 空白占位但不显示
		}
	}
	.week-day{
		color: #0055ff;
	}
</style>